package cn.disicn.service;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.collect.Lists;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.ehcache.CacheKit;

import cn.disicn.common.Const;
import cn.disicn.common.ServerResponse;
import cn.disicn.controller.SecPublishUserController;
import cn.disicn.model.SecPublishUser;
import cn.disicn.util.MD5Util;

/**
 * 
 * @author Luyao
 * @date 2017年11月25日 上午10:48:59
 * @desc:用户业务层
 */
public class SecPublishUserService {

	private static final Logger LOGGER = LoggerFactory.getLogger(SecPublishUserController.class);

	private static final SecPublishUser PUBLISH_USER = new SecPublishUser().dao();

	/**
	 * @desc:
	 * @date 2017年11月25日 下午3:04:00
	 * @param account
	 * @param password
	 * @param type
	 * @return
	 */
	public ServerResponse<SecPublishUser> login(String account, String password, String type) {
		// 判断账号是否存在
		if (!checkForExistence(account, type).isSuccess()) {
			LOGGER.error("用户不存在");
			return ServerResponse.createByErrorMsg("用户不存在");
		}
		// 将输入的密码用MD5加密
		String currentMd5Pwd = MD5Util.MD5EncodeUtf8(password);
		// 根据不同登录类型分别去数据库比对账号和密码
		StringBuilder sql = new StringBuilder("select * from sec_publish_user where password = ? and ");
		if (type.equals(Const.loginType.PHONE)) {
			sql.append("phone = ?");
		} else {
			sql.append("email = ?");
		}
		SecPublishUser user = PUBLISH_USER.findFirst(sql.toString(), currentMd5Pwd, account);
		// 判断匹配结果
		if (user != null) {
			if (Integer.parseInt(user.getStatus()) == Const.userStatusEnum.FROZEN.getCode()) {
				LOGGER.info("禁止登录");
				return ServerResponse.createByErrorMsg("该用户已禁止登录");
			}
			LOGGER.info("登录成功");
			return ServerResponse.createBySuccessMsg("登录成功", user);
		}
		LOGGER.error("密码错误");
		return ServerResponse.createByErrorMsg("密码错误");
	}

	/**
	 * 
	 * @desc:查询账号是否存在
	 * @date 2017年11月25日 下午3:18:18
	 * @param account
	 * @param type
	 * @return
	 */
	public ServerResponse<String> checkForExistence(String account, String type) {
		StringBuilder sql = new StringBuilder("select count(1) from sec_publish_user where ");
		if (type.equals(Const.loginType.PHONE)) {
			sql.append("phone = ?");
		} else {
			sql.append("email = ?");
		}
		Long count = Db.queryLong(sql.toString(), account);
		if (count > 0) {
			return ServerResponse.createBySuccessMsg("账号已存在");
		}
		return ServerResponse.createByErrorMsg("用户不存在");
	}

	/**
	 * 注册用户
	 */
	public ServerResponse<String> register(SecPublishUser user) {
		if (user.save()) {
			CacheKit.remove("SMSCode", user.getPhone());
			return ServerResponse.createBySuccessMsg("注册成功");
		}
		return ServerResponse.createByErrorMsg("注册失败");
	}

	/**
	 * 修改密码
	 */
	public ServerResponse<String> changePassword(SecPublishUser puser) {
		if (Db.update("update sec_publish_user set PASSWORD=? where phone=?", puser.getPassword(),
				puser.getPhone()) > 0) {
			return ServerResponse.createBySuccessMsg("修改成功");
		}
		return ServerResponse.createByErrorMsg("修改失败");
	}

	/**
	 * 修改头像
	 */
	public ServerResponse<String> uploadHeadImage(SecPublishUser puser) {
		if (Db.update("update sec_publish_user set headImgUrl=? where phone=?", puser.getHeadImgUrl(),
				puser.getPhone()) > 0) {
			return ServerResponse.createBySuccessMsg("修改成功");
		}
		return ServerResponse.createByErrorMsg("修改失败");
	}

	/**
	 * 修改用户名
	 */
	public ServerResponse<String> updUserName(SecPublishUser puser) {
		if (Db.update("update sec_publish_user set UserName=? where phone=?", puser.getUserName(),
				puser.getPhone()) > 0) {
			return ServerResponse.createBySuccessMsg("修改成功");
		}
		return ServerResponse.createByErrorMsg("修改失败");
	}

	/**
	 * 绑定新手机号
	 * 
	 * @param oldPhone
	 * @param phone
	 * @return
	 */
	public ServerResponse<String> changePhone(String oldPhone, String newPhone) {
		if (Db.update("update sec_publish_user set phone=? where phone=?", newPhone, oldPhone) > 0) {
			return ServerResponse.createBySuccessMsg("修改成功");
		}
		return ServerResponse.createByErrorMsg("修改失败");
	}

	/**
	 * 认证个人
	 */
	public ServerResponse<String> personal(SecPublishUser puser) {
		if (Db.update(
				"update sec_publish_user set realName=?,idCardFrontImgUrl=?,idCardBackImgUrl=?,auditStatus=?,idCardNumber=?,corporateName=?,attachmentUrl=? where phone=?",
				puser.getRealName(), puser.getIdCardFrontImgUrl(), puser.getIdCardBackImgUrl(), 0,
				puser.getIdCardNumber(), null, null, puser.getPhone()) > 0) {
			return ServerResponse.createBySuccessMsg("提交成功，等待审核");
		}
		return ServerResponse.createByErrorMsg("提交失败");
	}

	/**
	 * 认证企业
	 */
	public ServerResponse<String> company(SecPublishUser puser) {
		if (Db.update(
				"update sec_publish_user set realName=?,auditStatus=?,idCardNumber=?,corporateName=?,attachmentUrl=?,idCardFrontImgUrl=?,idCardBackImgUrl=? where phone=?",
				puser.getRealName(), 0, puser.getIdCardNumber(), puser.getCorporateName(), puser.getAttachmentUrl(),
				null, null, puser.getPhone()) > 0) {
			return ServerResponse.createBySuccessMsg("提交成功，等待审核");
		}
		return ServerResponse.createByErrorMsg("提交失败");
	}

	/**
	 * 保存邮箱账号
	 */
	public ServerResponse<String> changeEmail(String phone, String email) {
		if (Db.update("update sec_publish_user set email=? where phone=?", email, phone) > 0) {
			return ServerResponse.createBySuccess();
		}
		return ServerResponse.createByErrorMsg("邮箱修改失败");
	}

	/**
	 * 查询身份证的url
	 */
	public List<String> idCardImage(String phone) {
		List<String> list = Lists.newArrayList();
		List<SecPublishUser> secuser = PUBLISH_USER
				.find("select idCardFrontImgUrl,idCardBackImgUrl from sec_publish_user where phone=?", phone);

		if (secuser.size()>0) {
			for (SecPublishUser user : secuser) {
				if (!StringUtils.isBlank(user.getIdCardFrontImgUrl())) {
					list.add(user.getIdCardFrontImgUrl());
				}
				if (!StringUtils.isBlank(user.getIdCardBackImgUrl())) {
					list.add(user.getIdCardBackImgUrl());
				}
			}
		}
		
		if (list.size()>0) {
			return list;
		}
		return null;
	}
	
	/**
	 * 查询用户信息
	 */
	public ServerResponse findSecUserByPhone(String phone){
		List<SecPublishUser> secuser = PUBLISH_USER.find("select * from sec_publish_user where phone = ?",phone);
		if (secuser!=null) {
			return ServerResponse.createBySuccess(secuser.get(0));
		}
		return ServerResponse.createByErrorMsg("提交失败");
	}

}
